<template>
  <div id="public-message" ref="publicMsg">
    <p class="title">公众号消息</p>
    <div class="content_wrap ml10" :style="{height: height}">
      <el-main>
        <el-form :model="msgForm" :rules="rules" ref="msgForm" size="small" label-width="100px" class="push-form-box">
          <!-- 推送内容 -->
          <el-card class="box-card">
            <div slot="header" class="clearfix">
              <h2>推送内容</h2>
            </div>
            <div class="content">
              <el-row>
                <el-col :span="12">
                  <el-form-item label="服务号ID" prop="wx_appid">
                    <el-input placeholder="请填写公众号的OpenId" v-model="msgForm.wx_appid" :disabled="isNotEdit" @change="handleWxInfoChange"></el-input>
                  </el-form-item>
                </el-col>
                <el-col :span="6">
                  <template v-if="!appInfo">
                    <el-button size="small" type="primary" @click="handleBind">绑定</el-button>
                  </template>
                  <template v-else>
                    <el-button size="small" type="primary" @click="handleBindWxApp">{{ isNotEdit ? '编辑':'更绑' }}</el-button>
                    <template v-if="!isNotEdit">
                      <el-button size="small" type="primary" @click="unbindWexinApp">解绑</el-button>
                      <el-button size="small" type="primary" @click="isNotEdit=true">取消</el-button>
                    </template>
                  </template>
                </el-col>
              </el-row>
              <el-row v-if="!isNotEdit || !appInfo">
                <el-col :span="12">
                  <el-form-item label="服务号Key" prop="wx_secret_key">
                    <el-input placeholder="请填写公众号的SecretKey" v-model="msgForm.wx_secret_key" @change="handleWxInfoChange"></el-input>
                  </el-form-item>
                </el-col>
              </el-row>
              <template v-if="msgForm.audience_type === 'template'">
                <el-row>
                  <el-col :span="12">
                    <el-form-item label="相关链接">
                      <el-input v-model="msgForm.url" placeholder="请填写模板消息跳转的链接"></el-input>
                    </el-form-item>
                  </el-col>
                </el-row>
                <el-row>
                  <el-col :span="12">
                    <el-form-item label="模版ID" prop="template_id">
                      <el-input v-model="msgForm.template_id" placeholder="请填写模板消息ID"></el-input>
                    </el-form-item>
                  </el-col>
                </el-row>
                <el-row>
                  <el-col :span="12">
                    <el-form-item label="模板内容" prop="tempCont">
                      <el-input v-model="msgForm.tempCont" type="textarea" :autosize="{ minRows: 10, maxRows: 10}" placeholder="请填写模板内容，按照JSON格式传递"></el-input>
                    </el-form-item>
                  </el-col>
                </el-row>
              </template>
              <template v-else>
                <el-row>
                  <el-col :span="12">
                    <el-form-item label="通知类型">
                      <el-select v-model="msgForm.msgtype" placeholder="请选择推送的消息类型">
                        <el-option
                            v-for="item in msgTypes"
                            :key="item.index"
                            :label="item.label"
                            :value="item.value">
                        </el-option>
                      </el-select>
                    </el-form-item>
                  </el-col>
                </el-row>
                <template v-if="msgForm.msgtype === 'Text'">
                  <el-row>
                    <el-col :span="12">
                      <el-form-item label="通知内容" prop="content">
                        <el-input v-model="msgForm.content" type="textarea" :autosize="{ minRows: 10, maxRows: 10}" placeholder="请填写通知内容，字数在200个字以内"></el-input>
                      </el-form-item>
                    </el-col>
                  </el-row>
                </template>
                <!-- <template v-if="msgForm.msgtype === 'Mpnews'">
                  <el-row>
                    <el-col :span="12">
                      <el-form-item label="消息内容" prop="content">
                        <el-input v-model="msgForm.content" type="textarea" :autosize="{ minRows: 10, maxRows: 10}" placeholder="请填写通知内容，字数在200个字以内"></el-input>
                      </el-form-item>
                    </el-col>
                  </el-row>
                  <el-row>
                    <el-col :span="12">
                      <el-form-item label="图片上传">
                        <el-upload
                            class="upload-demo"
                            action="https://jsonplaceholder.typicode.com/posts/"
                            multiple
                            :file-list="fileList">
                          <el-button size="small" type="primary">点击上传</el-button>
                        </el-upload>
                      </el-form-item>
                    </el-col>
                  </el-row>
                </template>
                <template v-if="msgForm.msgtype === 'Image' || msgForm.msgtype === 'Mpvideo'">
                  <el-row>
                    <el-col :span="12">
                      <el-form-item :label="msgForm.msgtype === 'Image' ? '图片上传':'视频上传'">
                        <el-upload
                            class="upload-demo"
                            action="https://jsonplaceholder.typicode.com/posts/"
                            multiple
                            :file-list="fileList">
                          <el-button size="small" type="primary">点击上传</el-button>
                        </el-upload>
                      </el-form-item>
                    </el-col>
                  </el-row>
                </template>
                <template v-if="msgForm.msgtype === 'Voice'">
                  <el-row>
                    <el-col :span="12">
                      <el-form-item label="语音消息">
                        <el-upload
                            class="upload-demo"
                            action="https://jsonplaceholder.typicode.com/posts/"
                            multiple
                            :file-list="fileList">
                          <el-button size="small" type="primary">点击上传</el-button>
                        </el-upload>
                      </el-form-item>
                    </el-col>
                  </el-row>
                </template> -->
              </template>
              <el-form-item label="推送目标">
                <el-row>
                  <el-col :span="6">
                    <el-radio-group v-model="msgForm.audience_type" @change="handleAudienceType">
                      <el-radio-button label="all">全部用户</el-radio-button>
                      <el-radio-button label="des_user">特定用户</el-radio-button>
                      <el-radio-button label="template">模板消息</el-radio-button>
                    </el-radio-group>
                  </el-col>
                  <el-col :span="18">
                    <el-row>
                      <template v-if="msgForm.audience_type === 'all'">
                        <el-col :span="8">
                          <el-form-item>
                            <el-select placeholder="请选择群发类型" v-model="msgForm.isToAll" @change="handleSendType">
                              <el-option value="1" label="群发至所有用户"></el-option>
                              <el-option value="2" label="群发至指定标签用户群"></el-option>
                            </el-select>
                          </el-form-item>
                        </el-col>
                        <el-col :span="8">
                          <el-form-item prop="tag_id">
                            <template v-if="msgForm.isToAll === '1'"><i class="el-icon-warning"></i><span class="i-span">将对所有设备进行推送，请谨慎选择</span></template>
                            <el-input placeholder="请填写微信上的标签ID" v-model="msgForm.tag_id" v-else></el-input>
                          </el-form-item>
                        </el-col>
                      </template>
                      <template v-else>
                        <el-col :span="8">
                          <el-form-item prop="user_type">
                            <el-select placeholder="请选择特定用户" v-model="msgForm.user_type" @change="especiallyUser">
                              <el-option v-for="item in userArr" :key="item.index" :label="item.label" :value="item.value"></el-option>
                            </el-select>
                          </el-form-item>
                        </el-col>
                        <el-col :span="8" v-if="msgForm.user_type !== ''">
                          <el-form-item prop="touser">
                            <el-input v-if="msgForm.user_type === 'OpenId'" placeholder="请填写微信上的设备标识OpenId" v-model="msgForm.touser"></el-input>
                            <el-input v-else-if="msgForm.user_type === 'Token'" placeholder="请填写信鸽设备上的标识Token" v-model="msgForm.touser"></el-input>
                            <el-input v-else-if="msgForm.user_type === 'Account'" placeholder="请填写信鸽设备上的账号标识Account" v-model="msgForm.touser"></el-input>
                          </el-form-item>
                        </el-col>
                        <!-- <el-col :span="8">
                          <el-form-item>
                            <el-upload
                                class="upload-demo"
                                action="https://jsonplaceholder.typicode.com/posts/"
                                multiple
                                :file-list="fileList">
                              <el-button size="small" type="primary">点击上传</el-button>
                            </el-upload>
                          </el-form-item>
                        </el-col> -->
                      </template>
                    </el-row>
                  </el-col>
                </el-row>
              </el-form-item>
              <div class="form-buttons">
                <el-button type="primary" @click="handleChangeOpen" size="mini">确定推送</el-button>
              </div>
            </div>
          </el-card>
        </el-form>
      </el-main>
    </div>
    <!-- 下面放弹框 -->
    <el-dialog title="推送明细" :visible.sync="dialogPushVisible" width="600px">
      <el-main class="dialog-main">
        <el-row>
          <el-col :span="4">
            <span>消息类型：</span>
          </el-col>
          <el-col :span="19">
            <span v-if="msgForm.msgtype === 'Mpnews'">图文消息</span>
            <span v-else-if="msgForm.msgtype === 'Text'">文本消息</span>
            <span v-else-if="msgForm.msgtype === 'Image'">图片消息</span>
            <span v-else-if="msgForm.msgtype === 'Voice'">语音消息</span>
            <span v-else-if="msgForm.msgtype === 'Video'">视频消息</span>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="4">
            <span>推送目标：</span>
          </el-col>
          <el-col :span="19">
            <template v-if="msgForm.audience_type === 'all'">
              <span v-if="msgForm.isToAll === '1'">全部用户</span>
              <span v-else>指定微信标签用户群</span>
            </template>
            <span v-else-if="msgForm.audience_type === 'template'">模板消息， {{ this.msgForm.user_text }}</span>
            <span v-else>特定用户， {{ this.msgForm.user_text }}</span>
          </el-col>
        </el-row>
      </el-main>
      <template slot="footer" class="dialog-footer">
        <el-button @click="dialogPushVisible = false">取 消</el-button>
        <el-button type="primary" @click="handleConfirm">确 定</el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script type="text/ecmascript-6">
  import api from '../../../../api/url'
  import ajax from '../../../../api/ajax/mobilePushAjax'
  import { mapGetters } from 'vuex'
  import { Base64 } from 'js-base64'
  export default {
    name: 'notificatio-bar-message',
    data () {
      let checkJson = (rule, value, callback) => {
        if (typeof value === 'string') {
          try {
            let valObj = JSON.parse(value)
            if (valObj && typeof valObj === 'object') {
              callback()
            } else {
              callback(new Error('请输入正确的json字符串'))
            }
          } catch (e) {
            callback(new Error('请输入正确的json字符串'))
          }
        } else {
          callback()
        }
      }
      return {
        dialogPushVisible: false,
        userArr: [
          {label: '微信OpenId', value: 'OpenId'},
          {label: '信鸽Token', value: 'Token'},
          {label: '信鸽账号', value: 'Account'}
        ],
        isNotEdit: false,
        msgForm: {
          wx_appid: '',
          wx_secret_key: '',
          msgtype: 'Text',
          content: '',
          tempCont: '',
          isToAll: '1',
          audience_type: 'all',
          tag_id: '',
          user_type: 'OpenId',
          user_text: '微信OpenId',
          touser: '',
          url: '',
          template_id: ''
        },
        rules: {
          wx_appid: [
            { required: true, message: '请输入服务号ID', trigger: 'blur' }
          ],
          wx_secret_key: [
            { required: true, message: '请输入服务号Key', trigger: 'blur' }
          ],
          content: [
            { required: true, message: '请输入消息内容', trigger: 'blur' }
          ],
          tempCont: [
            { required: true, message: '请输入模板内容', trigger: 'blur' },
            { validator: checkJson, trigger: 'blur' }
          ],
          tag_id: [
            { required: false, message: '请输入微信标签ID', trigger: 'blur' }
          ],
          touser: [
            { required: true, message: '请输入微信ID、信鸽Token或信鸽Account', trigger: 'blur' }
          ],
          template_id: [
            { required: true, message: '请输入模版信息ID', trigger: 'blur' }
          ]
        },
        msgTypes: [
          { label: '文本消息', value: 'Text' }/* ,
          { label: '图文消息', value: 'Mpnews' },
          { label: '语音消息', value: 'Voice' },
          { label: '图片消息', value: 'Image' },
          { label: '视频消息', value: 'Mpvideo' } */
        ],
        appInfo: null,
        fileList: [],
        height: null
      }
    },
    computed: {
      ...mapGetters(['v3AppTitle', 'v3AppKey', 'v3SecretKey', 'v3platform'])
    },
    methods: {
      // 确定推送按钮
      handleChangeOpen () {
        this.$refs.msgForm.validate((valid) => {
          if (valid) {
            this.dialogPushVisible = true
          } else {
            return false
          }
        })
      },
      // 特殊用户触发
      especiallyUser () {
        switch (this.msgForm.user_type) {
          case 'OpenId':
            this.msgForm.user_text = '微信OpenId'
            break
          case 'Token':
            this.msgForm.user_text = '信鸽Token'
            break
          case 'Account':
            this.msgForm.user_text = '信鸽Account'
            break
          default:
            break
        }
      },
      // 处理绑定操作(更绑/绑定)
      handleBind () {
        if (this.appInfo) {
          this.isNotEdit = false
        } else {
          this.bindWexinApp()
        }
      },
      // 处理微信服务号更绑/绑定
      handleBindWxApp () {
        this.isNotEdit = false
        if (this.appInfo.wx_appid !== this.msgForm.wx_appid ||
        this.appInfo.wx_secret_key !== this.msgForm.wx_secret_key) {
          this.updateWexinAppInfo()
        }
      },
      // 处理微信服务号信息展示
      handleWxInfoChange (val) {
        if (val === '') {
          this.msgForm.wx_appid = this.appInfo.wx_appid
          this.msgForm.wx_secret_key = this.appInfo.wx_secret_key
        }
      },
      // 确定发送信息
      handleConfirm () {
        if (!this.appInfo) {
          this.bindWexinApp()
        }
        if (this.msgForm.audience_type === 'all') {
          this.sendWexinInfoAll()
        } else if (this.msgForm.audience_type === 'des_user') {
          this.sendWexinInfoToUser()
        } else if (this.msgForm.audience_type === 'template') {
          this.sendWexinInfoTemplate()
        }
        this.dialogPushVisible = false
      },
      // 处理推送目标变化
      handleAudienceType (val) {
        this.$refs.msgForm.clearValidate()
      },
      // 处理群发发送类型
      handleSendType (val) {
        this.$refs.msgForm.clearValidate()
        if (val === '2') {
          this.rules.tag_id[0].required = true
        } else {
          this.rules.tag_id[0].required = false
        }
      },
      // 绑定微信服务号
      bindWexinApp () {
        let _self = this
        let params = {
          wx_appid: this.msgForm.wx_appid,
          wx_secret_key: this.msgForm.wx_secret_key
        }
        this.ajaxPost(api.BIND_WEXIN_APP_ID, params, function (res) {
          if (res.ret_code === 0) {
            _self.isNotEdit = true
            _self.getWexinAppInfo()
            _self.$message({
              type: 'success',
              message: '绑定微信服务号成功'
            })
          }
        })
      },
      // 解绑微信服务号
      unbindWexinApp () {
        let _self = this
        let params = {
          wx_appid: this.appInfo.wx_appid,
          wx_secret_key: this.appInfo.wx_secret_key
        }
        this.ajaxPost(api.UNBIND_WEXIN_APP_ID, params, function (res) {
          if (res.ret_code === 0) {
            _self.$message({
              type: 'success',
              message: '解绑微信服务号成功'
            })
            _self.msgForm.wx_appid = ''
            _self.msgForm.wx_secret_key = ''
            _self.appInfo = null
          }
        })
      },
      // 查询微信服务号信息
      getWexinAppInfo (callback) {
        let _self = this
        this.ajaxPost(api.GET_WEXIN_APP_INFO, {}, function (res) {
          if (res.ret_code === 0) {
            _self.isNotEdit = true
            _self.msgForm.wx_appid = res.wx_appinfo.wx_appid
            _self.msgForm.wx_secret_key = res.wx_appinfo.wx_secret_key
            _self.appInfo = res.wx_appinfo
          }
        })
      },
      // 更新微信服务号信息
      updateWexinAppInfo () {
        let _self = this
        let params = {
          wx_appid: this.msgForm.wx_appid,
          wx_secret_key: this.msgForm.wx_secret_key
        }
        this.ajaxPost(api.UPDATE_WEXIN_APP_INFO, params, function (res) {
           _self.isNotEdit = true
          _self.getWexinAppInfo()
          if (res.ret_code === 0) {
            _self.$message({
              type: 'success',
              message: '更新微信服务号信息成功'
            })
          }
        })
      },
      // 全推接口
      sendWexinInfoAll () {
        let _self = this
        let filterObj = {}
        if (this.msgForm.isToAll === '1') {
          filterObj = {
            'is_to_all': true
          }
        } else {
          filterObj = {
            'is_to_all': false,
            'tag_id': this.msgForm.tag_id
          }
        }
        let params = {
          'filter': filterObj,
          'msgtype': this.msgForm.msgtype,
          'text': {
            'content': this.msgForm.content
          }
        }
        this.ajaxPost(api.SEND_WEXIN_INFO_ALL, params, function (res) {
          if (res.ret_code === 0) {
            _self.$message({
              type: 'success',
              message: '推送成功'
            })
            _self.resetForm()
          } else {
            _self.$message({
              type: 'error',
              message: res.err_msg
            })
          }
        })
      },
      // 指定用户推送接口
      sendWexinInfoToUser () {
        let _self = this
        let touser = this.msgForm.touser.split(',')
        let params = {
          'msgtype': this.msgForm.msgtype,
          'text': {
            'content': this.msgForm.content
          },
          'accout_type': 0,
          'touser': touser,
          'user_type': this.msgForm.user_type
        }
        this.ajaxPost(api.SEND_WEXIN_INFO_TO_USER, params, function (res) {
          if (res.ret_code === 0) {
            _self.$message({
              type: 'success',
              message: '推送成功'
            })
            _self.resetForm()
          } else {
            _self.$message({
              type: 'error',
              message: res.err_msg
            })
          }
        })
      },
      // 推送模板信息
      sendWexinInfoTemplate () {
        let _self = this
        let touser = this.msgForm.touser.split(',')
        if (touser.length > 1) {
          this.$message({
            type: 'warning',
            message: '模版消息同时只能发送给一个用户'
          })
          return false
        }
        let data = JSON.parse(this.msgForm.tempCont)
        let params = {
          'touser': touser[0],
          'user_type': this.msgForm.user_type,
          'account_type': 0,
          'template_id': this.msgForm.template_id,
          'data': data,
          'url': this.msgForm.url
        }
        this.ajaxPost(api.SEND_WEXIN_INFO_TEMPLATE, params, function (res) {
          if (res.ret_code === 0) {
            _self.$message({
              type: 'success',
              message: '推送成功'
            })
            _self.resetForm()
          } else {
            _self.$message({
              type: 'error',
              message: res.err_msg
            })
          }
        })
      },
      // 提交数据到后台
      ajaxPost (url, params, callback) {
        let h = {
          Authorization: 'Basic' + ' ' + Base64.encode(this.v3AppKey + ':' + this.v3SecretKey),
          'Content-Type': 'application/json'
        }
        ajax.post(url, params, h).then(res => {
          if (typeof callback === 'function') {
            callback(res)
          }
        })
      },
      // 重置表单
      resetForm () {
        this.$refs.msgForm.clearValidate()
        this.msgForm.user_type = 'OpenId'
        this.msgForm.user_text = '微信OpenId'
        if (this.msgForm.audience_type === 'template') {
          this.msgForm.tempCont = ''
          this.msgForm.url = ''
          this.msgForm.template_id = ''
          this.msgForm.touser = ''
        } else if (this.msgForm.audience_type === 'all') {
          this.msgForm.msgtype = 'Text'
          this.msgForm.content = ''
          this.msgForm.isToAll = '1'
          this.msgForm.tag_id = ''
        } else {
          this.msgForm.msgtype = 'Text'
          this.msgForm.content = ''
          this.msgForm.touser = ''
        }
      }
    },
    created () {
      this.getWexinAppInfo()
      this.$nextTick(() => {
        this.height = this.$refs.publicMsg.offsetHeight - 60 + 'px'
      })
    }
  }
</script>

<style lang="stylus" rel="stylesheet/stylus">
  #public-message
    height 100%
    background #f5f5f5
    overflow hidden
    .title
      height 60px
      padding 15px
      line-height 30px
      font-size 18px
      font-weight normal
      background #fff
    .content_wrap
      overflow auto
      .content
        background #fff
        .upload-demo
          display inline-block
        .i-span
          margin-left 8px
      .push-form-box
        .el-select,
        .el-date-editor,
        .el-input,
        .el-textarea,
        .el-radio-group
          display block
          width 100%!important
          padding 0 20px 0 0
          box-sizing border-box
        .el-select
          .el-input
            padding 0
        .el-radio-group
          .el-radio-button
            float left
            width 33.3%
            .el-radio-button__inner
              display block
              width 100%
        .form-buttons
          text-align center
    .el-dialog
      .dialog-main
        .el-row
          height 36px
          line-height 36px
          .el-col-4
            text-align right
</style>
